import BaseView from "../base/BaseView";

/*
 * @Author: mikey.ni 
 * @Date: 2018-5-14 10:24:46 
 * @Last Modified by: mikey.ni
 * @Last Modified time: 2019-01-14 10:41:20
 * @mailbox 769228622@qq.com
 */
const { ccclass } = cc._decorator;
@ccclass
export class CalendarView extends BaseView {
    private contenArr: Array<cc.Node> = []
    private lblYear: cc.Node = null;  //年月日显示
    private conten: cc.Node = null;
    private layblue: cc.Node = null;
    private lblLastMonth: cc.Label = null; //上个月
    private lblNextMonth: cc.Label = null; //下个月
    private currentMonth: number = 0; // 当前余额
    private newYear: number = 0;
    private newMonth: number = 0;
    private defauleDayTag: number = null;
    public lblCurrentTime: cc.Label = null; //当前选择时间文本 
    public nodeDayTime: cc.Node = null //今天时间

    /** 文本色值 */
    private get setectColor(): cc.Color { return new cc.Color().fromHEX("#FFF073") };
    private get defaultColor(): cc.Color { return new cc.Color().fromHEX("#FFF6E6") };
    private get disableColor(): cc.Color { return new cc.Color().fromHEX("#8F8F8F") };

    //限制天数查询
    public limitDayNum: number = 3600;
    /**
     * 时间工具
     */
    private uiltTime: UtilTime;

    private init() {
        this.uiltTime = new UtilTime();

        this.conten = this.sprBgNode.getChildByName("conten");
        this.lblYear = this.sprBgNode.getChildByName("lblYear");
        this.layblue = this.sprBgNode.getChildByName("layblue");
        this.nodeDayTime = this.sprBgNode.getChildByName("lblDayTime");

        let lblLastMonthNode: cc.Node = this.sprBgNode.getChildByName("lblLasttMonth");
        let lblNextMonthNode: cc.Node = this.sprBgNode.getChildByName("lblNextMonth");

        this.lblLastMonth = lblLastMonthNode.getComponent(cc.Label);
        this.lblNextMonth = lblNextMonthNode.getComponent(cc.Label);
        this.contenArr = this.conten.children;
        let lbl: cc.Label = null;

        for (let i = 0; i < this.contenArr.length; i++) {
            lbl = this.contenArr[i].getComponent(cc.Label);
            if (lbl) {
                lbl.overflow = cc.Label.Overflow.CLAMP;
                lbl.node.setContentSize(40, 40);
            }
        }
    }
    onLoad() {
        this.init();
        this.addEventNodeFun();
        // this.node.active = false;
    }

    onEnable() {
        this.initViewFun();
    }

    onDisable() {

    }
    onDestroy() {
        this.removeEventNodeFun();
    }

    private get sprBgNode(): cc.Node {
        return this.node.getChildByName("sprBg");
    }

    private addEventNodeFun() {   //添加监听事件
        let self = this;
        this.contenArr = this.conten.children;
        for (let i = 0; i < this.contenArr.length; i++) {
            this.contenArr[i].on(cc.Node.EventType.TOUCH_START, this.upEventReceiveFun, this);
            this.contenArr[i].on(cc.Node.EventType.TOUCH_END, this.upLayblueFun, this);
        }
        this.node.getChildByName("sprBg").on(cc.Node.EventType.TOUCH_START, function (event) {
            event.stopPropagation();
        }, this);
        this.node.getChildByName("eventBg").on(cc.Node.EventType.TOUCH_START, function (event) {
            event.stopPropagation();
            self.hide();
        }, this);
        this.nodeDayTime.on(cc.Node.EventType.TOUCH_END, this.onUpdateDayTime.bind(this));
    }
    private removeEventNodeFun() {
        this.contenArr = this.conten.children;

        if (!this.node.isValid) return;
        // for (let i = 0; i < this.contenArr.length; i++) {
        //     this.contenArr[i].off(cc.Node.EventType.TOUCH_START, this.upEventReceiveFun, this)
        //     this.contenArr[i].off(cc.Node.EventType.TOUCH_START, this.upLayblueFun, this)
        // }
        //  this.nodeDayTime.off(cc.Node.EventType.TOUCH_END, this.onUpdateDayTime.bind(this));
    }

    private onUpdateDayTime() {

        this.initViewFun();
    }

    private initViewCalendar(start: number, end: number, dcurrent: number = -1) {   //列表初始化

        let startS: number = (start == 7) ? 0 : start;//星期
        let k: number = 0;//当月天数；
        let upObj: any = this.getUpMonthMaxDay();
        let upDay: number = upObj.end - startS;//上个月补位天数
        let downDay: number = 0; //下个月补位天数
        for (let i: number = 0; i < this.contenArr.length; i++) {
            this.contenArr[i].getChildByName("lblYinli").getComponent(cc.Label).string = "";
            if (startS <= i && end + startS > i) {
                ++k;
                this.contenArr[i].name = k + "";
                if (k == dcurrent) {
                    this.defauleDayTag = i;
                }
                this.contenArr[i].getComponent(cc.Label).string = k.toString();
                // this.contenArr[i].getChildByName("lblYinli").getComponent(cc.Label).string = LunarDate.GetLunarDay(this.newYear, this.newMonth, k)

            } else {
                // this.contenArr[i].getComponent(cc.Label).string = "";    // !根据需求改变 
                if (i < startS) {       //上个月的补空位
                    ++upDay;
                    this.contenArr[i].name = (100 + upDay) + "";
                    this.contenArr[i].getComponent(cc.Label).string = upDay.toString();
                } else if (i >= end + startS) {  //下个月补空位
                    ++downDay;
                    this.contenArr[i].getComponent(cc.Label).string = downDay.toString();
                    this.contenArr[i].name = (200 + downDay) + "";
                }
            }
            this.setlblNodeColor(this.contenArr[i]);
        }
    }

    private setlblNodeColor(node: cc.Node): void {
        if (this.limitDayNum > 0) {
            let time: number = this.uiltTime.formatTimeStamp(this.getTimeFormat(node.name));
            let newTime: number = this.uiltTime.get1DayLastDate(new Date().getTime(), -this.limitDayNum);
            if (time >= newTime && time - newTime <= (this.limitDayNum + 1) * 24 * 3600 * 1000 - 1) {
                node.color = this.defaultColor;
            } else {
                node.color = this.disableColor;
            }
        } else {
            node.color = this.defaultColor;
        }
    }

    private initViewFun() { //初始化
        let date: Date = new Date()
        let severTime: string = this.uiltTime.formatYMD1(date);
        this.currentMonth = date.getMonth() + 1;
        this.updateMonth();
        this.lblYear.getComponent(cc.Label).string = severTime;
        let str = severTime.split("/")
        this.newYear = Number(str[0]);
        this.newMonth = Number(str[1]);
        let minAndMax: any = this.getTimeDataFun(this.newYear, this.newMonth)
        this.initViewCalendar(minAndMax.start, minAndMax.end, Number(str[2]));
        this.setLayblueState(this.contenArr[this.defauleDayTag]);
        this.lblYear.getComponent(cc.Label).string = this.uiltTime.formatYMD2(date);
        if (this.lblCurrentTime) {
            this.lblCurrentTime.string = this.uiltTime.formatYMD2(date);
        }
    }

    /** 设置选中块  */
    private _curSelectTarget: cc.Node;
    private setLayblueState(target: cc.Node): void {
        if (target) {
            if (this._curSelectTarget) {
                this._curSelectTarget.color = this.defaultColor;
            }
            this._curSelectTarget = target;
            target.color = this.setectColor;
            let nodeWordPos = this.conten.convertToWorldSpaceAR(target.getPosition());
            let myParentSpacePosition = this.sprBgNode.convertToNodeSpaceAR(nodeWordPos);
            this.layblue.setPosition(myParentSpacePosition);
        }
        this.layblue.active = target ? true : false;
    }

    private updateFun() {   //更新
        this.lblYear.getComponent(cc.Label).string = this.newYear + "/" + this.newMonth;
        let minAndMax: any = this.getTimeDataFun(this.newYear, this.newMonth)
        this.initViewCalendar(minAndMax.start, minAndMax.end)
    }

    private upLayblueFun(event) {
        if (!event.target.getComponent(cc.Label).string) return;
        if (event.target.color.equals(this.disableColor)) return;
        this.setLayblueState(event.target);
    }

    private upEventReceiveFun(event: cc.Event.EventTouch) {    //点击事件触发
        if (!event.target.getComponent(cc.Label).string) return;
        if (event.target.color.equals(this.disableColor)) return;
        let YearMD: string = "";
        YearMD = this.getTimeFormat(event.target.name);
        this.lblYear.getComponent(cc.Label).string = YearMD;
        if (this.lblCurrentTime) {
            this.lblCurrentTime.string = YearMD;
        }
    }

    private getTimeFormat(name: string): string {
        let tag: number = Number(name);
        let yearMonth: any = { yaer: 0, month: 0 };
        let day: number = 0;
        let YearMD: string = "";
        if (tag > 200) {
            day = Math.abs(tag - 200);
            yearMonth = this.downYaerMonthWayFun();
        } else if (tag > 100) {
            day = Math.abs(tag - 100);
            yearMonth = this.upYaerMonthWayFun();
        } else {
            day = tag;
            yearMonth.yaer = this.newYear;
            yearMonth.month = this.newMonth;
        }
        let monthStr: string = (yearMonth.month < 10 ? "0" : "") + yearMonth.month;
        let dayStr: string = (day < 10 ? "0" : "") + day;
        YearMD = yearMonth.yaer + monthStr + dayStr;
        return YearMD
    }

    private leftBtnFun() {
        if (this.reduceDateFun()) {
            this.setLayblueState(null);
            this.updateFun()
        } else {
            alert("超出日期范围")
        }
    }
    private rigthBtnFun() {
        this.setLayblueState(null);
        this.addDateFun();
        this.updateFun();
    }

    private reduceDateFun(): boolean {
        if (this.newMonth - 1 > 0) {
            this.newMonth -= 1;
            this.currentMonth = this.newMonth;
            this.updateMonth();
            return true
        } else {
            if (this.newYear - 1 > 1980) {
                this.newYear -= 1;
                this.newMonth = 12;
                this.currentMonth = this.newMonth;
                this.updateMonth();
                return true;
            } else {
                return false;
            }
        }
    }

    private addDateFun() {
        if (this.newMonth + 1 < 13) {
            this.newMonth += 1;
            this.currentMonth = this.newMonth;
            this.updateMonth();
        } else {
            this.newYear += 1;
            this.newMonth = 1
            this.currentMonth = this.newMonth;
            this.updateMonth();
        }
    }

    private updateMonth() {
        if (this.currentMonth == 12) {
            this.lblNextMonth.string = 1 + "月";
            this.lblLastMonth.string = (this.currentMonth - 1) + "月";
        } else if (this.currentMonth == 1) {
            this.lblNextMonth.string = (this.currentMonth + 1) + "月";
            this.lblLastMonth.string = 12 + "月";
        } else {
            this.lblNextMonth.string = (this.currentMonth + 1) + "月";
            this.lblLastMonth.string = (this.currentMonth - 1) + "月";
        }
    }

    private getTimeDataFun(yaer: number, month: number): any {
        let temp: Date = new Date(yaer, month, 0);
        let max: number = temp.getDate()
        temp.setDate(1)
        let min: number = temp.getDay()
        let bol: boolean = (yaer % 4 == 0 && yaer % 100 != 0) || yaer % 400 == 0;
        if (bol) {
            if (month == 2) {
                max = 29;
            }
        } else {
            if (month == 2) {
                max = 28;
            }
        }
        return { start: min, end: max }
    }

    private getUpMonthMaxDay(): any {
        let upYearMonth: any = {};
        upYearMonth = this.upYaerMonthWayFun()
        return this.getTimeDataFun(upYearMonth.yaer, upYearMonth.month)
    }

    private upYaerMonthWayFun(): object {
        let upYear: number = 0;
        let upMonth: number = 0
        if (this.newMonth == 1) {
            upYear = this.newYear - 1
            upMonth = 12;
        } else {
            upYear = this.newYear;
            upMonth = this.newMonth - 1;
        }
        return { yaer: upYear, month: upMonth }
    }
    private downYaerMonthWayFun(): object {

        let downYear: number = 0;
        let downMonth: number = 0
        if (this.newMonth == 12) {
            downYear = this.newYear + 1;
            downMonth = 1;
        } else {
            downYear = this.newYear;
            downMonth = this.newMonth + 1;
        }
        return { yaer: downYear, month: downMonth }
    }
    public show(cur:cc.Label) {
        this.lblCurrentTime = cur;
        if (!this.node.active) {
            this.node.active = true;
        }
    }
    public hide() {
        if (this.node.active) {
            this.node.active = false;
        }
        cc.sys.localStorage.setItem('Label_' + this.lblCurrentTime.node.name, this.lblCurrentTime.string);
    }
}
class UtilTime {
    /**
     * 年/月/日（例：2012/12/12）
     */
    public formatYMD1(date: Date): string {
        var time: string = date.getFullYear() + "/"
            + (date.getMonth() + 1) + "/"
            + date.getDate();
        return time;
    }

    /**
     * 年-月-日（例：20121212）
     */
    public formatYMD2(date: Date): string {
        var year: string = date.getFullYear().toString();
        var month: string = ((date.getMonth() + 1 < 10) ? "0" : "") + (date.getMonth() + 1);
        var day: string = ((date.getDate() < 10) ? "0" : "") + date.getDate();
        return year + month + day;
    }

    /**
     *转成时间戳 年-月-日  如 20180230
     * @
     * @param {string} formatTime
     * @memberof UtilTime
     */
    public formatTimeStamp(formatTime: string): number {
        let year = formatTime.slice(0,4);
        let month = formatTime.slice(4,6);
        let day = formatTime.slice(6,8);
        
        let date: Date = new Date(year + '-' + month + '-' + day);
        let time: number = date.getTime();
        return time;
    }

    /**
     * 获取时间戳 23：59：59 的 新的时间戳
     * @
     * @param {number} time
     * @param {number} [lastDay=1]
     * @returns {number}
     * @memberof UtilTime
     */
    public get1DayLastDate(time: number, lastDay: number = 1): number {
        let date: Date = new Date(time);
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        let newTime: number = date.getTime() + (lastDay * 24 * 3600 * 1000) - 1;
        return newTime;
    }
}